package cn.chint.manage.controller;

import java.io.File;
import java.io.IOException;  
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;  
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;  


  
/** 
 * Ajax异步上传图片 
 * 
 * @author Hang.W 
 * @version 1.0, 2017-02-14 00:51:39 
 */  
@Controller  
public class UploadPicController {  
	
	@Value("${chint.image.url}")
	private String image_url;
	
	@Value("${chint.image.path}")
	private String image_path;
	
	@Value("${chint.file.url}")
	private String file_url;
	
	@Value("${chint.file.path}")
	private String file_path;
	
	public Logger log = Logger.getLogger(getClass());
    /** 
     * 使用Ajax异步上传图片 
     *  
     * @param pic 封装图片对象 
     * @param request 
     * @param response 
     * @throws IOException  
     * @throws IllegalStateException  
     */  
    @RequestMapping(value = "/uploadPic", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void uploadPic(@RequestParam(value = "pic", required = false)MultipartFile pic, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {  
  
        try {  
            // 获取图片原始文件名  
            String originalFilename = pic.getOriginalFilename();  
       //     System.out.println(originalFilename);  
          
            // 文件名使用当前时间  
            String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());  
          
            // 获取上传图片的扩展名(jpg/png/...)  
            String extension = FilenameUtils.getExtension(originalFilename);  
              
            // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）  
            String path =  name + "." + extension;  
//            String imageUrl="http://localhost:8080/chint-dl/upload/"+ name + "." + extension; 
           

            // 图片上传的绝对路径  
            String url = image_path + path;  
            log.info(url);
          
            File dir = new File(url);  
            if(!dir.exists()) {  
               dir.mkdirs();  
            }  
              
            // 上传图片  
            pic.transferTo(new File(url));  
            log.info(path);
            // 将相对路径写回（json格式）  
            JSONObject jsonObject = new JSONObject();  
            // 将图片上传到本地  
            jsonObject.put("path", path); 
            String imageUrl= image_url+ path;
            jsonObject.put("imageUrl", imageUrl); 
            // 设置响应数据的类型json  
            response.setContentType("application/json; charset=utf-8");  
            // 写回  
            response.getWriter().write(jsonObject.toString());  
  
        } catch (Exception e) { 
        	e.printStackTrace();
            throw new RuntimeException("服务器繁忙，上传图片失败");  
        }  
    }  
    @RequestMapping(value = "/uploadFile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void uploadFile(@RequestParam(value = "file22", required = false)MultipartFile[]  files, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {  
  
        try {  
            // 获取图片原始文件名  
            String originalFilename = files[0].getOriginalFilename();  
            log.info(originalFilename);  
          
            // 文件名使用当前时间  
            String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());  
          
            // 获取上传图片的扩展名(jpg/png/...)  
            String extension = FilenameUtils.getExtension(originalFilename);  
              
            // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）  
            String path =  name + "." + extension;  
//            String fileUrl="http://localhost:8080/chint-dl/upload/"+ name + "." + extension; 
          //  String fileUrl="http://47.98.243.175/chint-dl/upload/"+ name + "." + extension;
            // 图片上传的绝对路径  
            String url = file_path + path;  
          
            File dir = new File(url);  
            if(!dir.exists()) {  
              dir.mkdirs();  
            }  
              
            // 上传图片  
            files[0].transferTo(new File(url));  
            log.info(path);
            // 将相对路径写回（json格式）  
            JSONObject jsonObject = new JSONObject();  
            // 将图片上传到本地  
            jsonObject.put("path", path);  
            String fileUrl=file_url+ path;
            jsonObject.put("fileUrl", fileUrl); 
            // 设置响应数据的类型json  
            response.setContentType("application/json; charset=utf-8");  
            // 写回  
            response.getWriter().write(jsonObject.toString());  
  
        } catch (Exception e) { 
        	e.printStackTrace();
            throw new RuntimeException("服务器繁忙，上传图片失败");  
        }  
    } 
      
}  
